from PIL import Image,ImageFilter
import pytesseract
from flask import Flask, request, render_template, jsonify
import os
app = Flask(__name__)
# 配置Tesseract OCR路径（根据实际安装路径修改）
pytesseract.pytesseract.tesseract_cmd = r'D:\tesseract\Tesseract-OCR\tesseract.exe'

@app.route('/', methods=['GET'])
def index():
    return render_template('upload.html')

@app.route('/upload', methods=['POST'])
def upload_file():
    if 'file' not in request.files:
        return jsonify({'error': 'No file uploaded'}), 400
    file = request.files['file']
    if file.filename == '':
        return jsonify({'error': 'No selected file'}), 400
    if file:
        # 保存上传的图片
        img_path = os.path.join('uploads', file.filename)
        file.save(img_path)
        # 处理图片并生成报告
        report, text = process_image(img_path)
        return jsonify({'report': report, 'text': text})

def process_image(image_path):
    """
    处理图片并生成报告
    """
    # 创建预处理图片保存目录
    preprocessed_dir = os.path.join('uploads', 'preprocessed')
    os.makedirs(preprocessed_dir, exist_ok=True)
    
    # 1. 图像预处理
    img = Image.open(image_path)
    

    # 图像增强处理
    img = img.convert('L')  # 转为灰度图
    
    # 1. 调整对比度
    from PIL import ImageEnhance
    enhancer = ImageEnhance.Contrast(img)
    img = enhancer.enhance(1.5)  # 增强对比度50%
    
    # 2. 应用锐化滤镜
    img = img.filter(ImageFilter.SHARPEN)
    
    # 3. 自动阈值二值化
    from PIL import ImageOps
    img = ImageOps.autocontrast(img, cutoff=5)
    
    # 4. 可选的光照校正(如果图像太暗)
    if img.getextrema()[1] < 100:  # 如果最大像素值小于100，认为图像太暗
        enhancer = ImageEnhance.Brightness(img)
        img = enhancer.enhance(1.5)  # 增加亮度50%
    
    # 保存预处理后的图片
    preprocessed_path = os.path.join(preprocessed_dir, 'preprocessed_' + os.path.basename(image_path))
    img.save(preprocessed_path)
    
    # 2. 使用Tesseract OCR识别文字
    # 配置Tesseract参数
    custom_config = r'--oem 3 --psm 6 -l chi_sim'
    text = pytesseract.image_to_string(img, config=custom_config)
    # print(text)
    # 3. 分析文本并生成报告
    # 读取关键词文件
    try:
        with open('deny_words.txt', 'r', encoding='utf-8') as f:
            deny_words = [line.strip().lower() for line in f.readlines() if line.strip()]
        with open('active_words.txt', 'r', encoding='utf-8') as f:
            active_words = [line.strip().lower() for line in f.readlines() if line.strip()]
    except UnicodeDecodeError:
        # 如果UTF-8解码失败，尝试其他编码
        try:
            with open('deny_words.txt', 'r', encoding='gbk') as f:
                deny_words = [line.strip().lower() for line in f.readlines() if line.strip()]
            with open('active_words.txt', 'r', encoding='gbk') as f:
                active_words = [line.strip().lower() for line in f.readlines() if line.strip()]
        except Exception as e:
            return {'error': f'文件读取失败: {str(e)}'}, ''
    # 判断激活状态
    # 规范化文本：移除所有空格、标点符号和特殊字符，统一小写
    import re
    # 改进的文本匹配算法
    from difflib import SequenceMatcher
    
    def fuzzy_match(word, text, threshold=0.7):
        """模糊匹配算法"""
        word = re.sub(r'[^\w]', '', word).lower()
        for i in range(len(text) - len(word) + 1):
            segment = text[i:i+len(word)]
            if SequenceMatcher(None, word, segment).ratio() >= threshold:
                return True
        return False
    
    # 规范化文本
    text_normalized = re.sub(r'[^\w]', '', text).lower()
    # print(f"规范化后的文本: {text_normalized}")
    # print(f"激活关键词列表: {active_words}")
    # print(f"禁止关键词列表: {deny_words}")
    
    has_deny_word = any(fuzzy_match(word, text_normalized) for word in deny_words)
    has_active_word = any(fuzzy_match(word, text_normalized) for word in active_words)
    # print(f"匹配到禁止关键词: {has_deny_word}")
    # print(f"匹配到激活关键词: {has_active_word}")
    
    report = {
        'activation_status': 'Windows未激活' if has_deny_word else ('Windows已激活' if has_active_word else 'Windows激活状态未知')
    }
    
    return report, text

def extract_info(text, keyword):
    """
    从文本中提取特定信息
    """
    lines = text.split('\n')
    for line in lines:
        if keyword in line:
            return line.strip()
    return '未找到相关信息'

if __name__ == '__main__':
    # 创建上传文件夹
    os.makedirs('uploads', exist_ok=True)
    app.run(debug=True)